//
//  SZZOAuthViewController.swift
//  SZZweibo
//
//  Created by 申壮壮 on 16/8/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking

class SZZOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        webView.delegate = self
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
        @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    // 自动填充
    @objc private func autofillAction(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        // js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    // 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SZZOAuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(SZZOAuthViewController.autofillAction))
        navigationItem.title = "微博登录"
    }
    
    //  懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
}

extension SZZOAuthViewController: UIWebViewDelegate {
    
    
       func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            
            if let query = request.URL?.query{
                
                let code = query.substringFromIndex("code=".endIndex)
                print("你是我的小呀小苹果:\(code)")
                getUserAccount(code)
            }
            
        }
        return true
    }
    
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
     
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
}

extension SZZOAuthViewController{
   
    func getUserAccount(code: String){
     
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id":WBAppKey,
            "client_secret": WBAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri": WBRedirect_uri
        ]
     
        let manager = AFHTTPSessionManager()
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            print("请求成功:\(response)")
           
            guard let res = response as? [String: AnyObject] else{
                return
            }
            
            let userAccount = SZZUserAccountViewModel.sharedTools.userAccount
            //print(userAccount)
            
        }) { (_, error) -> Void in
            print("请求失败:\(error)")
        }
        
    }
}

    
    


